<template>
  <div class="duty-roster">
    <!-- Header Info -->
    <el-card class="header-card" shadow="never">
      <div class="header-info">
        <div class="school-info">
        <!-- 搜索表单 -->
      <el-form
        :model="where"
        label-width="77px"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="5" :md="12">
            <el-form-item label="所属学校:">
              <el-select
                filterable
                clearable
                v-model="where.school_id"
                 @change="changeGradeAndEquip"
                size="small"
                placeholder="-请选择所属学校-"
                class="ele-block">
                <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :md="12">
            <el-form-item label="年级名称:">
              <el-select
                  filterable
                  clearable
                  v-model="where.grade_id"
                  @change="changeClass"
                  size="small"
                  placeholder="-请选择年级-"
                  class="ele-block">
                  <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :md="12">
            <el-form-item label="班级名称:">
              <el-select
                  filterable
                  clearable
                  v-model="where.class_id"
                  @change="changeStudent"
                  size="small"
                  placeholder="-请选择班级-"
                  class="ele-block">
                  <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="5" :md="12">
            <el-form-item label="设备:">
              <el-select
                  filterable
                  clearable
                  v-model="where.equip_id"
                  @change="$forceUpdate()"
                  size="small"
                  placeholder="-请选择设备-"
                  class="ele-block">
                  <el-option v-for="item in deviceList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :lg="4" :md="12">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
        </div>
      </div>
    </el-card>

    <!-- Duty Table -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
      :header-cell-style="headerStyle"
    >
      <el-table-column
        v-for="(day, dayIndex) in days"
        :key="dayIndex"
        :label="day.name"
        align="center"
      >
        <template slot="header" slot-scope="scope">
          <div class="column-header">
            <span>{{ day.name }}</span>
            <el-button
              type="text"
              icon="el-icon-setting"
              @click="handleSettings(dayIndex)"
              size="small"
            >
              设置
            </el-button>
          </div>
        </template>

        <template slot-scope="scope">
          <div v-if="scope.row[`day${dayIndex}`]" class="duty-cell">
            <div class="time">{{ scope.row[`day${dayIndex}`].start_time }}-{{ scope.row[`day${dayIndex}`].end_time }}</div>
            <div class="area">{{ scope.row[`day${dayIndex}`].area }}</div>
            <div class="students">{{ scope.row[`day${dayIndex}`].students }}</div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- Settings Dialog -->
    <el-dialog
      title="设置值日安排"
      :visible.sync="dialogVisible"
      width="650px"
    >
      <el-form :model="currentDay" label-width="80px">
        <div v-for="(duty, index) in currentDay.duties" :key="index" class="duty-form-item">
          <el-divider>值日时段 {{ index + 1 }}</el-divider>
          <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="起始时间">
                      <el-time-select
                        placeholder="起始时间"
                        v-model="duty.start_time"
                        :picker-options="{
                          start: '05:00',
                          step: '00:15',
                          end: '22:30'
                        }">
                      </el-time-select>
                  </el-form-item>
                </el-col>
               <el-col :span="12">

               <el-form-item label="结束时间">
                  <el-time-select
                    placeholder="结束时间"
                    v-model="duty.end_time"
                    :picker-options="{
                      start: '05:00',
                      step: '00:15',
                      end: '22:30',
                      minTime: duty.start_time
                    }">
                  </el-time-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="值日生">
                <el-select
                  v-model="duty.student_ids"
                  multiple
                  placeholder="请选择值日学生"
                >
                  <el-option
                    v-for="student in studentsList"
                    :key="student.id"
                    :label="student.name"
                    :value="student.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区域">
                <el-input v-model="duty.area" placeholder="请输入值日区域"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="duty-actions">
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="removeDuty(index)"
              >删除时段</el-button>
            </el-col>
          </el-row>
        </div>
        <div class="add-duty">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addDuty"
          >添加值日时段</el-button>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSettings">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'FlexibleDutyRoster',
  data() {
    return {
        temp: [
        {
          name: '星期一',
          duties: []
        },
        {
          name: '星期二',
          duties: []
        },
        {
          name: '星期三',
          duties: []
        },
        {
          name: '星期四',
          duties: []
        },
        {
          name: '星期五',
          duties: []
        },
        {
          name: '星期六',
          duties: []
        },
        {
          name: '星期天',
          duties: []
        }
      ],
      days: [
        {
          name: '星期一',
          duties: []
        },
        {
          name: '星期二',
          duties: []
        },
        {
          name: '星期三',
          duties: []
        },
        {
          name: '星期四',
          duties: []
        },
        {
          name: '星期五',
          duties: []
        },
        {
          name: '星期六',
          duties: []
        },
        {
          name: '星期天',
          duties: []
        }
      ],
      dayss: [
        {
          name: '星期一',
          duties: [
            {
              start_time: '07:30',
              end_time: '08:00',
              type: '早值日',
              students: '张三、李四',
              area: '教室、走廊',
              room: 'F03007'
            },
            {
              start_time: '11:30',
              end_time: '12:00',
              type: '午值日',
              students: '王五、赵六',
              area: '教室、黑板',
              room: 'F03007'
            }
          ]
        },
        {
          name: '星期二',
          duties: [
            {
              start_time: '07:30',
              end_time: '08:00',
              type: '早值日',
              students: '刘一、陈二',
              area: '教室、走廊',
              room: 'F03007'
            }
          ]
        },
        {
          name: '星期三',
          duties: [
            {
              start_time: '11:30',
              end_time: '12:00',
              type: '午值日',
              students: '张三、王五',
              area: '教室、黑板',
              room: 'F03007'
            },
            {
              start_time: '16:00',
              end_time: '16:30',
              type: '放学值日',
              students: '李四、赵六',
              area: '教室、走廊',
              room: 'F03007'
            },
            {
              start_time: '16:30',
              end_time: '17:00',
              type: '大扫除',
              students: '刘一、陈二',
              area: '整层楼',
              room: 'F03007'
            }
          ]
        },
        {
          name: '星期四',
          duties: [
            {
              start_time: '11:30',
              end_time: '12:00',
              type: '午值日',
              students: '张三、李四',
              area: '教室、走廊',
              room: 'F03007'
            }
          ]
        },
        {
          name: '星期五',
          duties: [
            {
              start_time: '15:30',
              end_time: '16:00',
              type: '放学值日',
              students: '王五、赵六、刘一、陈二',
              area: '教室、走廊',
              room: 'F03007'
            }
          ]
        },
        {
          name: '星期六',
          duties: []
        },
        {
          name: '星期天',
          duties: []
        }
      ],
      dialogVisible: false,
      currentDayIndex: 0,
      currentDay: {
        name: '',
        duties: []
      },
      studentsList: [],
       // 表格搜索条件
      where: {},
      // 学院列表
      schoolList: [],
        // 年级列表
      gradeList: [],
      // 班级列表
      classList: [],
       // 设备列表
      deviceList: [],
    }
  },
  computed: {
    tableData() {
      // Find the maximum number of duties across all days
      const maxDuties = Math.max(...this.days.map(day => day.duties.length))
      // Create rows based on the maximum number of duties
      return Array.from({ length: maxDuties }, (_, rowIndex) => {
        const rowData = {}
        this.days.forEach((day, dayIndex) => {
          rowData[`day${dayIndex}`] = day.duties[rowIndex] || null
        })
        return rowData
      })
    }

  },
  mounted() {
    this.getSchoolList(); // 查询学校列表
  },
  methods: {
    headerStyle() {
      return {
        background: '#f5f7fa',
        color: '#606266',
        padding: '8px',
        height: '50px'
      }
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      return {
        rowSpan: 1,
        colspan: 1
      }
    },
    handleSettings(dayIndex) {
      if (!this.days[dayIndex]) return
      this.currentDayIndex = dayIndex
      this.currentDay = JSON.parse(JSON.stringify(this.days[dayIndex]))
      // Add null check for duties
      if (!this.currentDay.duties) {
        this.currentDay.duties = []
      }
      this.dialogVisible = true
    },
    addDuty() {
      this.currentDay.duties.push({
        start_time: '08:00',
        end_time: '08:30',
        students: '',
        student_ids: [],
        area: '教室',
      })
    },
    removeDuty(index) {
      this.currentDay.duties.splice(index, 1)
    },
    saveSettings() {
      if (!this.currentDay || !this.currentDay.duties) return

      // 清理临时数据
      const updatedDuties = this.currentDay.duties.map(duty => {
        const { students, ...cleanDuty } = duty
        return cleanDuty
      })
      
      
      this.$http.post('/duty/edit',{school_id: this.where.school_id,grade_id: this.where.grade_id,class_id: this.where.class_id,equip_id: this.where.equip_id,what_day: this.currentDayIndex + 1,duties: updatedDuties}).then(res => {
        if (res.data.code === 0) {
          this.dialogVisible = false;
          this.$message({
            type: 'success',
            message: '值日安排已更新'
          })
          this.reload();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });

      
    },
    /* 刷新表格 */
    reload() {
        if(!this.where.school_id || !this.where.grade_id || !this.where.class_id || !this.where.equip_id){
            this.$message.error('请先按学校-年级-班级-班牌的层级选择');
            return;
        }
        this.$http.post('/duty/getDutyList',{school_id: this.where.school_id,grade_id: this.where.grade_id,class_id: this.where.class_id,equip_id: this.where.equip_id}).then(res => {
        if (res.data.code === 0) {
          this.days = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
      
    },
    /* 重置搜索 */
    reset() {
      this.where = {};
      this.days = this.temp;
    },
    changeGradeAndEquip(){
        this.where.grade_id = null;
        this.where.class_id = null;
        this.getGradeList();
        this.getDeviceList();
    },
    changeClass(){
        this.where.class_id = null;
        this.getClassList();
    },
    changeStudent(){
        this.$forceUpdate();
        this.studentsList = [];
        this.getStudentList();
    },
    /**
     * 获取学校列表
     */
    getSchoolList() {
      this.$http.get('/school/getSchoolList').then(res => {
        if (res.data.code === 0) {
          this.schoolList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
     /**
     * 获取年级列表
     */
    getGradeList() {
      this.$http.post('/grade/getGradeList',{oid:this.where.school_id}).then(res => {
        if (res.data.code === 0) {
          this.gradeList = res.data.data;
          this.$forceUpdate();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取班级列表
     */
    getClassList() {
      this.$http.post('/clazz/getClazzList',{gid:this.where.grade_id}).then(res => {
        if (res.data.code === 0) {
          this.classList = res.data.data;
          this.$forceUpdate();
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取设备列表
     */
    getDeviceList() {
      this.$http.post('/equip/getList',{organization: this.where.school_id}).then(res => {
        if (res.data.code === 0) {
          this.deviceList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
      
    },
    /**
     * 获取学生列表
     */
    getStudentList() {
      this.$http.post('/student/getList',{school_id: this.where.school_id,grade_id: this.where.grade_id,class_id: this.where.class_id}).then(res => {
        if (res.data.code === 0) {
          this.studentsList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
      
    },
  }
}
</script>

<style scoped>

.el-row {
    margin-top: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }

.duty-roster {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.school-info {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px;
}

.duty-slots {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px 8px;
}

.duty-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: left;
  padding: 8px;
  border-bottom: 1px solid #EBEEF5;
}

.duty-cell:last-child {
  border-bottom: none;
}

.time {
  color: #909399;
  font-size: 13px;
}

.duty-type {
  font-weight: 500;
  font-size: 14px;
}

.students {
  font-size: 13px;
}

.area, .room {
  color: #909399;
  font-size: 12px;
}

.duty-form-item {
  margin-bottom: 20px;
}

.duty-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.add-duty {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-divider--vertical) {
  margin: 0 8px;
}

:deep(.el-button--text) {
  padding: 0;
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-time-picker) {
  width: 100%;
}
</style>
